package com.zyf.pattern.template;

import com.zyf.pattern.proxy.cgilb.LiSi;
import com.zyf.pattern.template.entity.RowMapper;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * create by yifeng
 */
public class JdbcTemplate {
//public abstract class JdbcTemplate {
    private DataSource dataSource;

    public JdbcTemplate(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    private Connection getConnection() throws Exception{
        return this.dataSource.getConnection();
    }

    private PreparedStatement createPreparedStatement(Connection conn, String sql) throws SQLException {
        return conn.prepareStatement(sql);
    }

    private ResultSet executeQuery(PreparedStatement pstmt, Object[] values) throws SQLException {
        for (int i = 0; i < values.length; i++) {
            pstmt.setObject(i, values[i]);
        }
        return pstmt.executeQuery();
    }

    private void closeStatement(Statement stmt) throws Exception {
        stmt.close();
    }

    private void closeResult(ResultSet rs) throws Exception {
        rs.close();
    }

    private void closeConnection(Connection conn) throws Exception {
        // 放入连接池中
//        conn.close();
    }

    private List<?> parseResultSet(ResultSet rs, RowMapper rowMapper) throws SQLException {
        List<Object> result = new ArrayList<>();
        int rowNum = 1;
        while (rs.next()) {
            result.add(rowMapper.mapRow(rs, rowNum++));
        }
        return result;
    }


//    public List<Object> executeQuery(String sql, Object[] values) {
    public List<Object> executeQuery(String sql, RowMapper<?> rowMapper, Object[] values) {

        try {
        // 1. 获取连接
            Connection connection = this.getConnection();
        // 2. 创建语句集
            PreparedStatement pstmt = this.createPreparedStatement(connection, sql);
        // 3. 执行语句集，并且获得结果集
//            pstmt.setOb
            ResultSet resultSet = this.executeQuery(pstmt, values);
            // 4. 解析语句集
            List<?> objects = this.parseResultSet(resultSet, rowMapper);
            // 5. 关闭结果集
            this.closeResult(resultSet);
        // 6. 关闭语句集
            this.closeStatement(pstmt);
        // 7. 关闭连接
            this.closeConnection(connection);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

//    public abstract Object processResult(ResultSet rs, int rowNum) throws SQLException;




}
